package com.qa.music.ui.dashboard;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qa.music.R;
import com.qa.music.ui.PlayActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DashboardFragment extends Fragment {

    private DashboardViewModel dashboardViewModel;
    private Handler handler;
    private String[] strings1;
    ArrayAdapter<String> stringArrayAdapter;
    ArrayList<HashMap<String, String>> idlist = new ArrayList<>();
    ListView list;
    private String kerword = "流行";
    ProgressDialog progressDialog;

    /**
     * 圆圈加载进度的 dialog
     */
    private void showWaiting() {
        progressDialog = new ProgressDialog(getContext());
        progressDialog.setIcon(R.mipmap.ic_launcher);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("加载中...");
        progressDialog.setIndeterminate(true);// 是否形成一个加载动画  true表示不明确加载进度形成转圈动画  false 表示明确加载进度
        progressDialog.setCancelable(false);//点击返回键或者dialog四周是否关闭dialog  true表示可以关闭 false表示不可关闭
        progressDialog.show();
    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        dashboardViewModel =
                ViewModelProviders.of(this).get(DashboardViewModel.class);
        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);

        if(getArguments()!=null){
            kerword = getArguments().get("text").toString();
        }


        try {
            createlist(root);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return root;
    }

    public void createlist(final View view) throws IOException {


        String url = "https://music.2hakeji.com/findmusic";
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody formBody = new FormBody.Builder()
                .add("keyword", kerword)
                .add("page", "1")
                .add("pagesize", "100")
                .build();


        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        final ArrayList<String> strings = new ArrayList<>();
        list = view.findViewById(R.id.listView);

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0:
                        strings1 = strings.toArray(new String[strings.size()]);
                        stringArrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, strings1);
                        list.setOnItemClickListener((AdapterView<?> parent, View view, int position, long id) -> {
                            System.out.println(idlist.get(position));
//                            NavController navController = Navigation.findNavController(view);
//                            navController.navigate(R.id.navigation_notifications,args);
                            Intent intent = new Intent(getActivity(), PlayActivity.class);
                            HashMap<String, String> stringStringHashMap = idlist.get(position);
                            intent.putExtra("id", stringStringHashMap.get("id"));
                            intent.putExtra("name", stringStringHashMap.get("name"));
                            startActivity(intent);
                        });
                        list.setAdapter(stringArrayAdapter);
                        break;
                }
            }
        };
        showWaiting();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();

                JSONObject jsonObject = JSONObject.parseObject(string);
                JSONArray list1 = jsonObject.getJSONArray("list");

                for (int a = 0; a < list1.size(); a++) {
                    JSONObject jsonObject1 = list1.getJSONObject(a);
                    String s = jsonObject1.getString("gqm") + "-" + jsonObject1.getString("gs");
                    strings.add(s);
                    HashMap<String, String> objectObjectHashMap = new HashMap<>();
                    objectObjectHashMap.put("id", jsonObject1.getString("id"));
                    objectObjectHashMap.put("name", s);
                    idlist.add(objectObjectHashMap);

                }

                Message msg = new Message();
                msg.what = 0;
                handler.sendMessage(msg);
                progressDialog.cancel();
            }

        });

    }

}
